package com.zzl.study.sharding.algorithm.standard;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.math.BigInteger;
import java.util.Collection;
import java.util.Properties;

/**
 * @author: zhangzl
 * @date: 2022/7/17 11:59
 * @version: 1.0
 * @description: 书本表自定义类分片算法：standard策略，对书本表的adminId进行行表达式分片，不支持范围查询
 */
public class BookInlineStandardShardingAlgorithm implements StandardShardingAlgorithm<Long> {

    /**
     * 配置的props属性
     */
    private Properties props;

    /**
     * 分片个数，写死6个
     */
    private final int shardingCount = 6;

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        Long adminId = shardingValue.getValue();
        String suffix = new BigInteger(adminId.toString()).mod(new BigInteger(String.valueOf(this.shardingCount))).toString();
        return findMatchedTargetName(availableTargetNames, suffix, shardingValue.getDataNodeInfo()).orElse(null);
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Long> shardingValue) {
        throw new UnsupportedOperationException("根据admin_id取模算法不支持范围查询!");
    }

    @Override
    public Properties getProps() {
        return this.props;
    }

    @Override
    public void init(Properties props) {
        this.props = props;
    }

}
